//
//  ProfileTableViewController.m
//  Gradekeeper0.2
//
//  Created by Lily Wang on 11/2/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//  reference: http://broadcast.oreilly.com/2009/06/tab-bars-and-navigation-bars-t.html
//  reference: http://stackoverflow.com/questions/259956/nsstring-tokenize-in-objective-c
//  reference: http://blog.ablepear.com/2009/06/nsmutablearray-and-removeobjectatindex.html
//  reference: http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html

#import "ProfileTableViewController.h"
#import "ProfileDetailViewController.h"
#import "Gradekeeper0_2AppDelegate.h"
#import "ProfileController.h"
#import "fileIO.h"
#import "Profile.h"
#import <Foundation/NSObject.h>

@implementation ProfileTableViewController
@synthesize profileArray;
@synthesize pDetailViewController;
@synthesize profileController;


- (void) setRow: (NSUInteger) inputRow{
	rowToDelete = inputRow;
}
- (NSUInteger) getRow{
	return rowToDelete;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    
	// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
	
	
	// create a custom navigation bar button and set it to say "Log Out"
	UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
	temporaryBarButtonItem.title = @"Log Out";
	self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
	[temporaryBarButtonItem release];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	NSString *profileManager = @"profileManager";
	NSString *tempProfileList = nil;
	
	if ([fileIO fileExist:profileManager]){
		tempProfileList = [[NSString alloc] initWithFormat:@"%@", [fileIO readFromFile:profileManager]];
	}
	else {
		[fileIO writeToFile:profileManager : @""];
	};
	
	NSArray *tempArray = [tempProfileList componentsSeparatedByString: @":"];
	NSMutableArray *profileList = [[NSMutableArray alloc] initWithCapacity:1];
	
	
	for (int y = 1; y < [tempArray count]; y ++){
		[profileList addObject: [tempArray objectAtIndex:y]];
	};
	
	
	[tempProfileList release];
	
	self.profileArray = profileList;
	[profileList release];
	
	[self.tableView reloadData];
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
	[super setEditing:editing animated:animated];
	if(editing) {
		self.navigationItem.rightBarButtonItem.enabled = NO;
	} else {
		self.navigationItem.rightBarButtonItem.enabled = YES;
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/* the following functions applies to table view*/

//Set up table view
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.profileArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	NSUInteger row = [indexPath row];
	cell.textLabel.text = [profileArray objectAtIndex:row];
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	NSInteger row = [indexPath row];
	NSString *selectedProfile = [NSString stringWithFormat:@"%@", [profileArray objectAtIndex:row]];													   
	
	if (self.pDetailViewController == nil){
		ProfileDetailViewController *profileDetail = [[ProfileDetailViewController alloc] initWithNibName:@"ProfileDetailView" bundle:nil];
	
		self.pDetailViewController = profileDetail;
		[profileDetail release];
	}
		
	pDetailViewController.title = selectedProfile;
	
	Profile *profile = [Profile sharedProfile];
	[profile setUserName:selectedProfile];
	
	[self.navigationController pushViewController:pDetailViewController animated:YES];

}

- (UITableViewCellAccessoryType)tableView:(UITableView *)tv accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellAccessoryDisclosureIndicator;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/ 


// Override to support editing the table view.

//Set up alert button function
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:@"Delete Confirmation"]){
		if (buttonIndex == 0) {
			
			NSFileManager  *NSFm;
			
			NSFm = [NSFileManager defaultManager] ;
			
			NSString *temp = [NSString stringWithFormat:@"%@", [profileArray objectAtIndex:rowToDelete]];
			
			
			[NSFm removeItemAtPath:[fileIO getFilePath:temp] error:NULL] ;
			
			[fileIO deleteFromFile:@"profileManager" :temp :@":"];
			[self.profileArray removeObjectAtIndex:rowToDelete];
			[self.tableView reloadData];
		}
		
	} 
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		rowToDelete = indexPath.row;
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Delete Confirmation" 
							  message:@"Are you sure you would like to delete your profile? \n All information stored under the profile will be deleted." 
							  delegate:self
							  cancelButtonTitle:@"Yes" 
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"No"];
			
		[alert show];
		
		[alert release];
		
		[self.tableView reloadData];
	
		
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
	[profileController release];
	[pDetailViewController release];
    [super dealloc];
}

- (IBAction) createPressed:(id)sender {
	if (self.profileController == nil){
		ProfileController *pController= [[ProfileController alloc] initWithNibName:@"Profile" bundle:nil];
		self.profileController = pController;
		[pController release];
		 
	}
	
	[self.navigationController pushViewController:profileController animated:YES];
	

}



@end

